package com.cuijq.counterv2.utils;

import com.cuijq.counterv2.entity.RequestInfo;
import com.cuijq.counterv2.entity.RequestStat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Classname Aggregator
 * @Description TODO
 * @Date 2021/4/30 14:13
 * @Created by CuiJQ
 */
public class Aggregator {

  public Map aggregate(Map<String, List<RequestInfo>> requestInfos, long durationInMillis) {
    Map requestStats = new HashMap<>();
    for (Map.Entry<String, List<RequestInfo>> entry : requestInfos.entrySet()) {
      String apiName = entry.getKey();
      List requestInfosPerApi = entry.getValue();
      RequestStat requestStat = doAggregate(requestInfosPerApi, durationInMillis);
      requestStats.put(apiName, requestStat);
    }
    return requestStats;
  }

  private RequestStat doAggregate(List requestInfos, long durationInMillis) {
    List respTimes = new ArrayList<>();
    for (RequestInfo requestInfo : (List<RequestInfo>) requestInfos) {
      double respTime = requestInfo.getResponseTime();
      respTimes.add(respTime);
    }
    RequestStat requestStat = new RequestStat();
    requestStat.setMaxResponseTime(max(respTimes));
    requestStat.setMinResponseTime(min(respTimes));
    requestStat.setAvgResponseTime(avg(respTimes));
    requestStat.setP999ResponseTime(percentile999(respTimes));
    requestStat.setP99ResponseTime(percentile99(respTimes));
    requestStat.setCount(respTimes.size());
    requestStat.setTps((long) tps(respTimes.size(), durationInMillis / 1000));
    return requestStat;
  }

  private double max(List dataset) {
    return Double.parseDouble(null);
  }

  private double min(List dataset) {
    return Double.parseDouble(null);
  }

  private double avg(List dataset) {
    return Double.parseDouble(null);
  }

  private double tps(int count, double duration) {
    return Double.parseDouble(null);
  }

  private double percentile999(List dataset) {
    return Double.parseDouble(null);
  }

  private double percentile99(List dataset) {
    return Double.parseDouble(null);
  }

}